import { useState } from "react";

const loaders = {};

function LazyChart({ lib, name, ...props }) {
    const [Chart, setChart] = useState(null);

    loaders[lib].then(() => setChart(window[lib][name]));

    if (Chart === null) {
        return <div>Loading</div>;
    } else {
        return <Chart {...props} />;
    }
}

const AntdCharts = {
    // 统计图表
    Plots(names) {
        if (!loaders.Plots) loaders.Plots = window.MP.load(['Base/@ant-design/plots@2.2.2/dist/plots.min.js']);
        return names.map(name => {
            if (window.Plots) return window.Plots[name];
            return props => <LazyChart lib="Plots" name={name} {...props} />;
        });
    },

    // 地图
    Maps(names) {
        if (!loaders.Maps) loaders.Maps = window.MP.load(['Base/@ant-design/maps@1.0.8/dist/maps.min.js', 'Base/@ant-design/maps@1.0.8/dist/runtime.min.js']);
        return names.map(name => {
            if (window.Maps) return window.Maps[name];
            return props => <LazyChart lib="Maps" name={name} {...props} />;
        });
    },

    // 关系图
    Graphs(names) {
        if (!loaders.Graphs) loaders.Graphs = window.MP.load(['Base/@ant-design/graphs@1.4.1/dist/graphs.min.js', 'Base/@ant-design/graphs@1.4.1/dist/runtime.min.js']);
        return names.map(name => {
            if (window.Graphs) return window.Graphs[name];
            return props => <LazyChart lib="Graphs" name={name} {...props} />;
        });
    },
};

export default AntdCharts;